package processor

import (
	"fmt"
	"sync"
)

// Processor is an interface for data processors
type Processor interface {
	// Init initializes the processor
	Init(config map[string]interface{}) error
	// Process processes data
	Process(data []byte, metadata map[string]string) ([]byte, error)
	// Close closes the processor
	Close() error
}

// ProcessorFactory is a function that creates a processor
type ProcessorFactory func() (Processor, error)

var (
	// processorFactories is a map of processor factories
	processorFactories = make(map[string]ProcessorFactory)
	// mu is a mutex for protecting the factories
	mu sync.RWMutex
)

// RegisterProcessorFactory registers a processor factory
func RegisterProcessorFactory(name string, factory ProcessorFactory) {
	mu.Lock()
	defer mu.Unlock()
	processorFactories[name] = factory
}

// GetProcessorFactory gets a processor factory
func GetProcessorFactory(name string) ProcessorFactory {
	mu.RLock()
	defer mu.RUnlock()
	return processorFactories[name]
}

// ListProcessorTypes lists all processor types
func ListProcessorTypes() []string {
	mu.RLock()
	defer mu.RUnlock()
	types := make([]string, 0, len(processorFactories))
	for t := range processorFactories {
		types = append(types, t)
	}
	return types
}

// NewProcessor creates a new processor
func NewProcessor(processorType string) (Processor, error) {
	factory := GetProcessorFactory(processorType)
	if factory == nil {
		return nil, fmt.Errorf("unknown processor type: %s", processorType)
	}
	return factory()
}
